<?php
    define('DIR_LIB', realpath(dirname(__file__) . '/../../../../../../lib') . '/');
    define('DIR_CONFIG', realpath(dirname(__file__) . '/../../../configs') . '/');
    define('DIR_OPT', realpath(dirname(__file__) . '/options') . '/');
	define('DIR_CACHE', realpath(dirname(__file__) . '/cache') . '/');
	define('DIR_LOGS', realpath(dirname(__file__) . '/logs') . '/');
	define('LOG_FILE', DIR_LOGS . 'logs.log');
    define('DIR_TMP', realpath(dirname(__file__) . '/tmp') . '/');
    define('DIR_TRAD', realpath(dirname(__file__) . '/trad') . '/');
    define('DIR_JDB', realpath(dirname(__file__) . '/db') . '/');
    define('DIR_PLUGIN', realpath(dirname(__file__)) . '/');

    class WZ_Utils extends Zend_Controller_Plugin_Abstract
    {
        const CLASS_PLUGIN_APPEND = 'ModuleBootstrap';
        private $_cache;
        public static $_view;
        public $_request;
        public $_response;
        public $_dispatcher;
        public $_defaultModule;
        private static $_logger;
        
        public function routeStartup(Zend_Controller_Request_Abstract $request)
        {
            $this->autoload();
            $clonedRequest = clone $request;
            Zend_Registry::set('originalRequest', $clonedRequest);    
            $config = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getOptions();
            
            $appName = $config['WZ']['appName'];
            define('PAGE_DEFAULT', $config['resources']['frontController']['defaultControllerName']);
            define('ACTION_DEFAULT', $config['resources']['frontController']['defaultAction']);
            define('MODULE_DEFAULT', $config['resources']['frontController']['defaultModule']);
            define('DIR_FILES', realpath(dirname(__file__) . '/../../../../../../public/' . $appName . '/assets') . '/');
            setvar('**config**', parse_ini_file(Zend_Registry::get('WZConfigPath') . APPLICATION_ENV . '.ini'));
            $this->autoload('Exception');
            $this->autoload('Locale');
            $this->autoload('Date');
            $this->_cache = Zend_Registry::get('WZCache');
            $this->autoload('Model');
            $this->autoload('WZModel');
            $this->autoload('Tree');
        }
     
        public function routeShutdown(Zend_Controller_Request_Abstract $request)
        {
            $module = $request->getModuleName();
            $action = $request->getActionName();
            $controller = $request->getControllerName();
            
            if ($action != 'login' && $action != 'forget-login') {
                $auth = Zend_Auth::getInstance();
                if (!$auth->hasIdentity()) {
                    $action = 'login';
                    $controller = 'static';
                    $request->setModuleName($module)->setControllerName($controller)->setActionName($action)->setDispatched(false);
                }
            }
            
            Zend_Registry::set('WZModule', $module);
            Zend_Registry::set('WZAction', $action);
            Zend_Registry::set('WZController', $controller);
            
            $moduleDir = Zend_Controller_Front::getInstance()->getModuleDirectory($module);
            $moduleBootClass = ucfirst(strtolower($module)) . self::CLASS_PLUGIN_APPEND;
            $moduleBootFile  = $moduleDir . '/' . $moduleBootClass . '.php';
            
            if(file_exists($moduleBootFile)) {
                require_once $moduleBootFile;
                if (!class_exists($moduleBootClass, false)) {
                    throw new Zend_Application_Bootstrap_Exception("Class $moduleBootClass not found in $moduleBootFile");
                }

                $bootObject = new $moduleBootClass('');
                if (!$bootObject instanceof Zend_Application_Bootstrap_BootstrapAbstract) {
                    throw new Zend_Application_Bootstrap_Exception("Class $moduleBootClass must inherit from Zend_Application_Bootstrap_BootstrapAbstract");
                }
                
                $bootObject->bootstrap();
            }
        }
     
        public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
        {
            
        }
     
        public function preDispatch(Zend_Controller_Request_Abstract $request)
        {
            
        }
     
        public function postDispatch(Zend_Controller_Request_Abstract $request)
        {
            if (true === Zend_Registry::isRegistered('isTemplating')) {
                if (true === Zend_Registry::get('isTemplating')) {
                    $this->getResponse()->setBody(self::parsePhp($this->getResponse()->getBody()));
                }
            }
        }
     
        public function dispatchLoopShutdown()
        {

        }
        
        public function action($controller, $action, $module = null, array $params = array())
        {
            $front = Zend_Controller_Front::getInstance();
            $response = $front->getResponse();
            $request  = $front->getRequest();
            $this->_request       = clone $request;
            $this->_response      = clone $response;
            $this->_dispatcher    = clone $front->getDispatcher();
            $this->_defaultModule = $front->getDefaultModule();
            
            self::resetObjects();
            if (null === $module) {
                $module = $this->_defaultModule;
            }

            // clone the view object to prevent over-writing of view variables
            $viewRendererObj = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
            Zend_Controller_Action_HelperBroker::addHelper(clone $viewRendererObj);

            $this->_request->setParams($params)->setModuleName($module)->setControllerName($controller)->setActionName($action)->setDispatched(true);

            $this->_dispatcher->dispatch($this->_request, $this->_response);

            // reset the viewRenderer object to it's original state
            Zend_Controller_Action_HelperBroker::addHelper($viewRendererObj);


            if (!$this->_request->isDispatched() || $this->_response->isRedirect()) {
                return '';
            }

            $return = $this->_response->getBody();
            self::resetObjects();
            return self::parsePhp($return);
        }
        
        public function resetObjects()
        {
            $params = $this->_request->getUserParams();
            foreach (array_keys($params) as $key) {
                $this->_request->setParam($key, null);
            }

            $this->_response->clearBody();
            $this->_response->clearHeaders()
                           ->clearRawHeaders();
        }
        
        public static function template($bool, $view = null)
        {
            Zend_Registry::set('isTemplating', $bool);
            self::$_view = $view;
        }
        
        public function getPost($val = null)
        {
            if (isset($_POST)) {
                if (null !== $val) {
                    if (isset($_POST[$val])) {
                        return $_POST[$val];
                    }
                } else {
                    return $_POST;
                }
            } else {
                return null;
            }
        }
        
        public function getGet($val = null)
        {
            if (isset($_GET)) {
                if (null !== $val) {
                    if (isset($_GET[$val])) {
                        return $_GET[$val];
                    }
                } else {
                    return $_GET;
                }
            } else {
                return null;
            }
        }
        
        public function getSession($val = null)
        {
            $session = self::session();
            if (null !== $val) {
                if (isset($session->$val)) {
                    return $session->$val;
                } else {
                    return null;
                }
            } else {
                return $session;
            }
        }
        
        public function setSession($name, $value)
        {
            $session = self::session();
            $session->$name = $value;
        }
        
        public function parsePhp($val)
        {
            if (!is_utf8($val)) {
                $val = utf8_encode($val);
            }
            $retour = _r('_("', '<?php echo __("', $val);
            $retour = _r('")_', '"); ?>', $retour);
            $retour = _r("_('", '<?php echo __("', $retour);
            $retour = _r("')_", '"); ?>', $retour);
            $retour = _r('{{=', '<?php echo ', $retour);
            $retour = _r('{{', '<?php ', $retour);
            $retour = _r('}}', '?>', $retour);
            
            $tab = explode('££', $retour);
            if (sizeof($tab) > 1) {
                for ($i = 1 ; $i < sizeof($tab) ; $i++) {
                    $seg = trim($tab[$i]);
                    list($chaine, $dummy) = explode('§§', $seg, 2);
                    $retour = _r('££' . $chaine . '§§', '<?php echo __("' . sl($chaine) . '"); ?>', $retour);
                }
            }
            $retour = self::recupeval($retour);
            return $retour;
        }
        
        function addAsset($file, $ext = null)
        {
            if(null === $ext) {
                $tabExt = explode('.', $file);
                $ext = end($tabExt);
            }
            $ct = @file_get_contents($file);
            if (strlen($ct)) {
                if(strstr($ct, '{{')) {
                    $ct = self::parsePhp($ct);
                }
                $hash = md5($ct);
                $tmpFile = DIR_FILES . 'tmp/' . $hash . '.' . $ext;
                if (!is_file($tmpFile)) {
                    @touch($tmpFile);
                    file_put_contents($tmpFile, $ct);
                }
                return URL_SITE . 'tmp/' . $hash . '.' . $ext;
            } else {
                return $file;
            }
        }
        
        public function recupeval($php)
        {
            $scriptphp = DIR_CACHE . md5($php) . '.php';
            @touch($scriptphp);
            file_put_contents($scriptphp, $php);
            ob_start();
            $view = $this->_view;
            $wz = clone $this;
            include($scriptphp);
            $result = ob_get_contents();
            ob_end_clean();
            @unlink($scriptphp);
            return $result;
        }
        
        public function autoload($plugin = null)
        {
            if (null === $plugin) {
                require_once(DIR_LIB . 'gp/functions.php');
                load('option');
                load('dbcache');
                load('trad');
                load('bigfile');
                load('db');
                load('app');
                load('debug');
                load('hook');
                load('jdb');
                load('mongo');
                load('cache');
                load('vars');
                get_vars();
                purge();
                
                //traductions
                $trad = GP_jdb::getInstance('translations', $lng);
                Zend_Registry::set('WZTrad', $trad);
                
                $url_site = "http://" . $_SERVER["SERVER_NAME"] . dirname($_SERVER["SCRIPT_NAME"]);
                if ($url_site[strlen($url_site) - 1] == '\\') {
                    $url_site = substr($url_site, 0, -1);
                }
                $url_site .= '/';
                    
                if (strstr($url_site, '//')) {
                    $url_site = _r('//', '/', $url_site);
                    $url_site = _r(':/', '://', $url_site);
                }

                define('URL_SITE', $url_site);
                $uri = substr($_SERVER['REQUEST_URI'], 1, strlen($_SERVER['REQUEST_URI']));
                define('DOCUMENTURL', $url_site . $uri);
            } else {
                $plugin = DIR_PLUGIN . $plugin;
                if (is_file($plugin . '.php')) {
                    require_once $plugin . '.php';
                }
            }
        }
        
        public function loadForm($form, $return = true)
        {
            $file = Zend_Registry::get('WZFormsPath') . $form . '.php';
            if (is_file($file)) {
                require_once $file;
                if (true === $return) {
                    $className = 'WZForm_' . $form;
                    $form = new $className();
                    return $form;
                }
            }
        }

        public function loadModel($model, $return = true)
        {
            $file = Zend_Registry::get('WZModelsPath') . $model . '.php';
            if (is_file($file)) {
                require_once $file;
                if (true === $return) {
                    $className = 'WZModel_' . $model;
                    $model = new $className();
                    return $model;
                }
            }
        }
        
        public function link($controller, $action = null)
        {
            if (null === $action) {
                $action = 'index';
            }
            return URL_SITE . $controller . '/' . $action . '.html';
        }
        
        public function urlizer($routeName, $params = array(), $urlSite = true, $ext = true)
        {
            return makeUrlRouteZend($routeName, $params, $urlSite, $ext);
        }
        
        public function isPage($routeName, $onlyController = true)
        {
            $route = getRouteByName($routeName);
            
            $routeController = $route['defaults.controller'];
            $routeAction = $route['defaults.action'];
            $routeModule = $route['defaults.module'];
            if ($routeModule == Zend_Registry::get('WZModule')) {
                if (true === $onlyController) {
                    if ($routeController == Zend_Registry::get('WZController')) {
                        return true;
                    }
                }
            }
            return false;
            // return isPage(Zend_Registry::get('WZController'), Zend_Registry::get('WZAction'));
        }
        
        public static function session($namespace = 'WZSession')
        {
            if (false === Zend_Registry::isRegistered($namespace)) {
                Zend_Registry::set($namespace, new Zend_Session_Namespace($namespace));
            }
            return Zend_Registry::get($namespace);
        }
        
        
        public function db()
        {
            $config = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getOptions();
            $user = $config['resources']['db']['params']['username'];
            $password = $config['resources']['db']['params']['password'];
            $dbName = $config['resources']['db']['params']['dbname'];
            $host = $config['resources']['db']['params']['host'];
            $dsn = "mysql:dbname=$dbName;host=$host";
            $db = GP_db::getInstance($dsn, $user, $password);
            return $db;
        }
        
        public function ZendDb()
        {
            $config = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getOptions();
            $user = $config['resources']['db']['params']['username'];
            $password = $config['resources']['db']['params']['password'];
            $dbName = $config['resources']['db']['params']['dbname'];
            $host = $config['resources']['db']['params']['host'];
            
            $paramsdb = array (
                'host'     => $host,
                'username' => $user,
                'password' => $password,
                'dbname'   => $dbName
            );
            $db = Zend_Db::factory('PDO_MYSQL', $paramsdb);
            $db->getConnection();
            Zend_Db_Table::setDefaultAdapter($db);
            Zend_Db_Table::setDefaultMetadataCache($this->_cache);
            $db->setFetchMode(Zend_Db::FETCH_OBJ);
            $db->setProfiler(true);
            Zend_Registry::set('ZendDb', $db);
        }
        
        public static function getLogger()
        {
            if (null === self::$_logger) {
                $stream = @fopen(LOG_FILE, 'a', false);
                if (!$stream) {
                    throw new WZ_Exception('Failed to open stream');
                }
                 
                $writer = new Zend_Log_Writer_Stream($stream);
                self::$_logger = new Zend_Log($writer); 
            }
            return self::$_logger;
        }
        
        public static function setView($var, $val)
        {
            setvar('page' . ucfirst(strtolower($var)), $val);
        }
        
        public static function title($title)
        {
            self::setView('title', $title);
        }
        
        public static function keywords($keywords)
        {
            self::setView('keywords', $keywords);
        }
        
        public static function description($description)
        {
            self::setView('description', $description);
        }
        
        public static function makeKey($value)
        {
            return sha1($value . date('dmY') . 'AJFPRO789321555');
        }
        
        public static function checkKey($value, $key)
        {
            $checkKey = self::makeKey($value);
            return ($key == $checkKey) ? true : false;
        }
        
        public static function log($data, $extras = null)
        {
            self::getLogger()->log($data, Zend_Log::INFO, $extras);
        }
        
        public static function dump()
        {
            $headers = apache_request_headers();
            $args = func_get_args();
            self::log($args[0]);
            print_r($headers['X-Requested-With']);
            if ((isset($headers['X_REQUESTED_WITH']) && $headers['X_REQUESTED_WITH'] == 'XMLHttpRequest') ||
                 isset($headers['X-REQUESTED-WITH']) && $headers['X-REQUESTED-WITH'] == 'XMLHttpRequest'  ||
                 isset($headers['X_Requested_With']) && $headers['X_Requested_With'] == 'XMLHttpRequest'  ||
                 isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest' ) {

                print_r($args[0]);
                return;
            }
            Zend_Debug::dump($args[0], $args[1]);
        }
    }